package edu.dublbo.generator.common.interceptor;

import edu.dublbo.generator.common.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author habitplus
 * @since 2020-12-27 22:05
 */
public class JwtInterceptor extends HandlerInterceptorAdapter {
    public static final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("正在拦截：{}, {}", request.getRequestURI(),request.getServletPath());
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer:")) {
            return false;
        }

        // 获得 token
        String token = authHeader.substring(7);
        return jwtUtils.verify(token);
    }
}
